package com.example.blue_plugin.sdk;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.contec.bc.code.bean.ContecBluetoothType;
import com.contec.bc.code.callback.BluetoothSearchCallback;
import com.contec.bc.code.callback.CommunicateCallback;
import com.contec.bc.code.connect.ContecSdk;

import org.json.JSONArray;
import org.json.JSONObject;

public class NiaoYeSDK {
    public Activity activity;
    private ContecSdk sdk = new ContecSdk();
    private boolean isConnect;

    public NiaoYeSDK(Activity activity) {
        this.activity = activity;
        sdk.init(ContecBluetoothType.TYPE_FF, false);
        initRescevier();
    }

    private void initRescevier() {
        BluetoothMonitorReceiver bleListenerReceiver = new BluetoothMonitorReceiver();
        IntentFilter intentFilter = new IntentFilter();
        // 监视蓝牙关闭和打开的状态
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        // 监视蓝牙设备与APP连接的状态
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        // 注册广播
        activity.registerReceiver(bleListenerReceiver, intentFilter);
    }

    class BluetoothMonitorReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case BluetoothAdapter.ACTION_STATE_CHANGED:
                        int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);

                        if (blueState == BluetoothAdapter.STATE_OFF) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(context, "蓝牙已关闭", Toast.LENGTH_LONG).show();
                                }
                            });


                        }
                        break;

                    case BluetoothDevice.ACTION_ACL_CONNECTED:

                        break;

                    case BluetoothDevice.ACTION_ACL_DISCONNECTED:

                        break;
                }

            }
        }
    }

    public void searchBlutoothList() {
//        setBtn("连接中"); //todo 连接中
        showLog("连接中");
        if (listener != null) {
            listener.stateMsg("1", "连接中");
        }
        //初始化蓝牙模块
        sdk.startBluetoothSearch(new BluetoothSearchCallback() {
            @Override
            public void onContecDeviceFound(com.contec.bc.code.base.ContecDevice bluetoothDevice) {
                Log.e("stf", "设备名字 = " + bluetoothDevice.getName());
                if (!TextUtils.isEmpty(bluetoothDevice.getName())) {
                    Log.i("stf", "-是否当前设备-->" + bluetoothDevice.getName().contains("BC01"));
                    if (bluetoothDevice.getName().contains("BC")) {
                        sdk.stopBluetoothSearch();
                        if (!isConnect) {
                            isConnect = true;
                            sdk.setObtainDataType(ContecSdk.ObtainDataType.SINGLE);
                            sdk.startCommunicate(activity, bluetoothDevice, communicateCallback);
                        }
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (listener != null) {
                                    listener.stateMsg("2", "采集中");
                                }
                            }
                        });
                    }
                }
            }

            @Override
            public void onSearchError(int i) {
                Log.i("stf", "--onSearchError-->" + i);
                isConnect = false;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        setBtn("重新\n连接");
                        showLog("重新连接");
                        if (listener != null) {
                            listener.stateMsg("4", "重新\n连接");
                        }
                    }
                });
            }

            @Override
            public void onSearchComplete() {
                Log.i("stf", "--onSearchComplete-->");
            }
        }, 60000);
    }

    CommunicateCallback communicateCallback = new CommunicateCallback() {

        @Override
        public void onCommunicateDisplaySuccess(String DisplayData) {
            Log.i("stf", "--onCommunicateDisplaySuccess-DisplayData-->" +DisplayData);
            try {
                isConnect = false;
                if(listener != null){
                    listener.stateMsg("2","重新\n采集");
                    JSONObject jsonObject = new JSONObject(DisplayData);
                    JSONArray displayData = jsonObject.optJSONArray("DisplayData");
                    JSONObject jsonObject1 = displayData.optJSONObject(0);
                    String json = jsonObject1.toString();
                    Log.i("stf", "--onCommunicateDisplaySuccess-DisplayData处理后-->" +json);
                    listener.onCommunicateDisplaySuccess(json);
                }

//                UrineAnalyzerDevBean devBean = new Gson().fromJson(DisplayData, UrineAnalyzerDevBean.class);
//                List<UrineAnalyzerDevBean.DisplayDataBean> displayData = devBean.getDisplayData();
//                activity.runOnUiThread(() -> {
//                    if (displayData == null) {
//                        activity.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                showLog("数据返回错误，请重试");
//                            }
//                        });
//                        return;
//                    }
////
////                    UrineAnalyzerDevBean.DisplayDataBean displayDataBean = displayData.get(0);
////                    if (displayDataBean == null) {
////                        showLog("数据返回错误，请重试");
////                        return;
////                    }
//
////                    String URO = displayDataBean.getURO().getInternationUnit();
////                    String LEU = displayDataBean.getLEU().getInternationUnit();
////                    String NIT = displayDataBean.getNIT().getInternationUnit();
////                    String BLD = displayDataBean.getBLD().getInternationUnit();
////                    String GLU = displayDataBean.getGLU().getInternationUnit();
////                    String SG = displayDataBean.getSG().getInternationUnit();
////                    String BIL = displayDataBean.getBIL().getInternationUnit();
////                    String PRO = displayDataBean.getPRO().getInternationUnit();
////                    String VC = displayDataBean.getVC().getInternationUnit();
////                    String KET = displayDataBean.getKET().getInternationUnit();
////                    String PH = displayDataBean.getPH().getInternationUnit();
//
////                    displayDateDEBean = displayDataBean;
////
//////                    setBtn("重新\n采集");
////                    showLog("重新采集");
////                    if (getIsEmpty(URO)) {
////                        tvUro.setText("-");
////                        tvMUro.setText("-");
////                    } else {
////                        tvMUro.setText(getValue(URO));
////                        tvUro.setText(getValueReplace(URO));
////                    }
////
////                    if (getIsEmpty(LEU)) {
////                        tvLeu.setText("-");
////                        tvMLeu.setText("-");
////                    } else {
////                        tvMLeu.setText(getValue(LEU));
////                        tvLeu.setText(getValueReplace(LEU));
////                    }
////
////
////                    if (getIsEmpty(NIT)) {
////                        tvNit.setText("-");
////                        tvMNit.setText("-");
////                    } else {
////                        tvMNit.setText(getValue(NIT));
////                        tvNit.setText(getValueReplace(NIT));
////                    }
////
////                    if (getIsEmpty(BLD)) {
////                        tvBld.setText("-");
////                        tvMBld.setText("-");
////                    } else {
////                        tvMBld.setText(getValue(BLD));
////                        tvBld.setText(getValueReplace(BLD));
////                    }
////
////                    if (getIsEmpty(GLU)) {
////                        tvGlu.setText("-");
////                        tvMGlu.setText("-");
////                    } else {
////                        tvMGlu.setText(getValue(GLU));
////                        tvGlu.setText(getValueReplace(GLU));
////                    }
////
////                    if (getIsEmpty(SG)) {
////                        tvSg.setText("-");
////                        tvMSg.setText("-");
////                    } else {
////                        tvSg.setText(getValue(SG));
////                        tvMSg.setText(getValue(SG));
////                    }
////
////                    if (getIsEmpty(BIL)) {
////                        tvBil.setText("-");
////                        tvMBIl.setText("-");
////                    } else {
////                        tvMBIl.setText(getValue(BIL));
////                        tvBil.setText(getValueReplace(BIL));
////                    }
////
////                    if (getIsEmpty(PRO)) {
////                        tvPro.setText("-");
////                        tvMPro.setText("-");
////                    } else {
////                        tvMPro.setText(getValue(PRO));
////                        tvPro.setText(getValueReplace(PRO));
////                    }
////
////                    if (getIsEmpty(VC)) {
////                        tvVc.setText("-");
////                        tvMVc.setText("-");
////                    } else {
////                        tvMVc.setText(getValue(VC));
////                        tvVc.setText(getValueReplace(VC));
////                    }
////
////                    if (getIsEmpty(KET)) {
////                        tvKet.setText("-");
////                        tvMket.setText("-");
////                    } else {
////                        tvMket.setText(getValue(KET));
////                        tvKet.setText(getValueReplace(KET));
////                    }
////
////                    if (getIsEmpty(PH)) {
////                        tvPh.setText("-");
////                        tvMPh.setText("-");
////                    } else {
////                        tvPh.setText(getValue(PH));
////                        tvMPh.setText(getValue(PH));
////                    }
//
////                    commit.setEnabled(true);
////                    commit.setBackground(getResources().getDrawable(R.drawable.corners_green_check));
//                });
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }

        @Override
        public void onCommunicateIndexSuccess(final String indexJson) {
            isConnect = false;
            showLog("onCommunicateIndexSuccess:\n" + indexJson);
            Log.i("stf", "--onCommunicateIndexSuccess-indexJson-->" + indexJson);
        }

        @Override
        public void onCommunicateSuccess(final String json) {
            isConnect = false;
            Log.i("stf", "--onCommunicateSuccess-json-->" + json);
        }

        @Override
        public void onCommunicateFailed(int errorCode) {
            Log.i("------", "onCommunicateFailed->" + errorCode);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    setBtn("重新\n连接");
                    showLog("重新\n连接");
                    if (listener != null) {
                        listener.stateMsg("4", "重新\n连接");
                    }
                }
            });

            isConnect = false;
        }

        @Override
        public void onCommunicateProgress(int status) {
            Log.i("------", "onCommunicateProgress->" + status);
            if (status == 5) {
                isConnect = false;
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLog("设备已断开");
//                        if (listener != null) {
//                            listener.stateMsg("5", "设备\n已断开");
//                        }
                    }
                });
            }
        }
    };

    private void showLog(String s) {
        Log.i("stf", "--尿液设备-->" + s);
    }

    public void onDestroyCon() {
        if (sdk != null) {
            sdk.stopBluetoothSearch();
            sdk.stopCommunicate();
        }
    }

    public interface OnResultListener {
        void onCommunicateDisplaySuccess(String json);

        void onCommunicateIndexSuccess(String json);

        void stateMsg(String state, String msg);
    }

    public OnResultListener listener;

    public void setOnResultListener(OnResultListener listener) {
        this.listener = listener;
    }
}
